package com.mall.common.exception;

import com.mall.common.result.Result;
import com.mall.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数验证异常
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = { BindException.class, MethodArgumentNotValidException.class })
    public Result<Object> handleValidException(Exception e) {
        log.error("参数校验异常", e);
        BindingResult bindingResult = null;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        } else if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        if (bindingResult != null && bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return Result.failed(ResultCode.VALIDATE_FAILED.getCode(), fieldError.getDefaultMessage());
            }
        }
        return Result.failed(ResultCode.VALIDATE_FAILED);
    }

    /**
     * 处理业务异常
     *
     * @param e 业务异常
     * @return 结果
     */
    @ExceptionHandler(value = BizException.class)
    public Result<Object> handleBizException(BizException e) {
        log.error("业务异常", e);
        if (e.getCode() != null) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return Result.failed(e.getMessage());
    }

    /**
     * 处理系统异常
     *
     * @param e 系统异常
     * @return 结果
     */
    @ExceptionHandler(value = SysException.class)
    public Result<Object> handleSysException(SysException e) {
        log.error("系统异常", e);
        if (e.getCode() != null) {
            return Result.failed(e.getCode(), e.getMessage());
        }
        return Result.failed(ResultCode.FAILED.getCode(), "系统异常，请联系管理员");
    }

    /**
     * 处理其他异常
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error("未知异常", e);
        return Result.failed("系统异常，请联系管理员");
    }
}